package com.gz.WeChatSys.service.impl;

import com.gz.WeChatSys.config.MapCacheManager;
import com.gz.WeChatSys.dao.WxUserMapper;
import com.gz.WeChatSys.model.*;
import com.gz.WeChatSys.service.*;
import com.gz.WeChatSys.utils.RandomUtils;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.*;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutTextMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;


/**
 * @author lydia
 * @date 2018/10/15 上午10:30
 * @discription
 */
@Service
public class WxMsgServiceImpl extends WxMpMessageRouter implements WxMsgService {

    @Resource
    private WxUserService wxUserService;
    @Resource
    private WxUserMapper userMapper;
    @Resource
    private WxMpAutoreplyService wxMpAutoreplyService;
    @Resource
    private WxMpDialogService wxMpDialogService;
    @Resource
    private WxMpMsgService wxMpMsgService;


    public WxMsgServiceImpl(WxMpService wxMpService) {
        super(wxMpService);
    }

    public void prepare(boolean async, StringBuffer sb, WxMpMessageRouter router) {
        router.rule().async(async).msgType(WxConsts.XML_MSG_EVENT).event(WxConsts.EVT_SUBSCRIBE).handler(new WxSubscribeHandler(1)).end()
                .rule().async(async).msgType(WxConsts.XML_MSG_EVENT).event(WxConsts.EVT_UNSUBSCRIBE).handler(new WxSubscribeHandler(0)).end()
                .rule().async(async).msgType(WxConsts.XML_MSG_EVENT).event(WxConsts.EVT_CLICK).eventKey("kfzn").handler(new WxSubscribeHandler(3)).end()
                .rule().async(async).msgType(WxConsts.XML_MSG_TEXT).rContent("^\\d{1,2}$").handler(new WxSubscribeHandler(4,sb.toString())).end()
                .rule().async(async).msgType(WxConsts.XML_MSG_TEXT).rContent("^\\d{4}$").handler(new WxSubscribeHandler(5,sb.toString())).end()
                .rule().async(async).msgType(WxConsts.XML_MSG_TEXT).rContent("ly.*$").handler(new WxSubscribeHandler(6,sb.toString())).end()
                .rule().async(async).msgType(WxConsts.XML_MSG_TEXT).handler(new WxSubscribeHandler(9,sb.toString())).end();
    }


    @Override
    public WxMpXmlOutMessage handlerMsg(WxMpService wxCpService, WxMpXmlMessage message) {
        StringBuffer sb = new StringBuffer();
        sb.append(1);
        if(StringUtils.isNoneBlank(message.getContent())){
            sb.append(message.getContent());
        }
        WxMpMessageRouter router = new WxMpMessageRouter(wxCpService);
        prepare(false, sb, router);
        return router.route(message);
    }

    public class WxSubscribeHandler implements WxMpMessageHandler {
        private Integer subscribe;
        private String id;

        public WxSubscribeHandler(Integer subscribe) {
            this.subscribe = subscribe;
        }
        public WxSubscribeHandler(Integer subscribe,String id) {
            this.subscribe = subscribe;
            this.id = id;
        }

        @Override
        public WxMpXmlOutMessage handle(WxMpXmlMessage wxMpXmlMessage, Map<String, Object> map, WxMpService wxMpService, WxSessionManager wxSessionManager) throws  WxErrorException {
            String userOpenId = wxMpXmlMessage.getFromUser();
            WxMpUser user = wxMpService.getUserService().userInfo(userOpenId);
            if (subscribe == 1 || subscribe == 3) {
                //关注
//                WxMpUser user = wxMpService.getUserService().userInfo(userOpenId);

                //查一下是否已经在数据库
                if ((wxUserService.getWxUser(userOpenId)) != null) {
                    userMapper.updateSubscribe(userOpenId, subscribe);
                    String content = "您好，欢迎再次使用不动产在线沟通平台！很高兴为您服务！请回复数字选择您要咨询的业务类型范围！\n";
                    content = generateContent(content);
                    WxMpXmlOutTextMessage m = WxMpXmlOutMessage.TEXT().content(content)
                            .fromUser(wxMpXmlMessage.getToUser())
                            .toUser(userOpenId).build();

                    return m;
                } else {
                    WxUser wxUser = new WxUser();
                    wxUser.setOpenId(user.getOpenId());
                    wxUser.setNickName(user.getNickname());
                    wxUser.setSubscribe(subscribe);
                    wxUser.setHeadImgUrl(user.getHeadImgUrl());
                    wxUserService.insert(wxUser);

                    String content = "您好，欢迎使用不动产在线沟通平台！很高兴为您服务！请回复数字选择您要咨询的业务类型范围！\n";
                    content = generateContent(content);
                    WxMpXmlOutTextMessage m = WxMpXmlOutMessage.TEXT().content(content)
                            .fromUser(wxMpXmlMessage.getToUser())
                            .toUser(userOpenId).build();
                    return m;
                }
            }else if(subscribe == 4){
                //插入会话信息
                WxMpDialog wxMpDialog = new WxMpDialog();
                String dialogId = RandomUtils.getOrderNo();
                wxMpDialog.setId(dialogId);
                Long currentTime = System.currentTimeMillis();
                SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                wxMpDialog.setDialogName(format.format(currentTime) + user.getNickname() + "的咨询会话");
                wxMpDialogService.insert(wxMpDialog);

                MapCacheManager cacheManager = MapCacheManager.getInstance();
                cacheManager.updateCache("dialogId", dialogId);

                //插入消息信息
                inserMsg(id.substring(1),userOpenId,user.getNickname(),"在线沟通平台");

                List<WxMpAutoreply> autoreplyList = wxMpAutoreplyService.getAutoreplyByType(Integer.parseInt(id.substring(1)));
                String content = "您好，请回复数字选择您要咨询的问题！\n";
                if(autoreplyList.size()>0){
                    for(WxMpAutoreply wxMpAutoreply:autoreplyList){
                        content += "【"+ wxMpAutoreply.getId() + "】" + wxMpAutoreply.getQuestion() + "\n" ;
                    }
                }else{
                    content = "抱歉，暂未您所选类型的问题咨询,如有问题请拨打咨询电话96510";
                }

                //插入消息信息
                inserMsg(content,wxMpXmlMessage.getToUser(),"在线沟通平台",user.getNickname());

                WxMpXmlOutTextMessage m = WxMpXmlOutMessage.TEXT().content(content)
                        .fromUser(wxMpXmlMessage.getToUser())
                        .toUser(userOpenId).build();
                return m;
            }else if(subscribe == 5){
                //插入消息信息
                inserMsg(id.substring(1),userOpenId,user.getNickname(),"在线沟通平台");

                WxMpAutoreply autoreply = wxMpAutoreplyService.getAutoreplyInfo(Integer.parseInt(id.substring(1)));
                String content = "";
                if(ObjectUtils.allNotNull(autoreply)){
                        content = autoreply.getAnswer() + "\n如您还有疑问请拨打咨询电话96510或留言（留言请以ly开头并提供联系方式）";
                }else{
                    content = "抱歉，暂未您所选问题的解答,如有问题请拨打咨询电话96510";
                }
                //插入消息信息
                inserMsg(content,wxMpXmlMessage.getToUser(),"在线沟通平台",user.getNickname());

                WxMpXmlOutTextMessage m = WxMpXmlOutMessage.TEXT().content(content)
                        .fromUser(wxMpXmlMessage.getToUser())
                        .toUser(userOpenId).build();
                return m;
            }else if(subscribe == 6){
                //插入消息信息
                inserMsg(id.substring(1),userOpenId,user.getNickname(),"在线沟通平台");

                String content = "已收到您的留言，请保持电话畅通我们将尽快与您联系";
                WxMpXmlOutTextMessage m = WxMpXmlOutMessage.TEXT().content(content)
                        .fromUser(wxMpXmlMessage.getToUser())
                        .toUser(userOpenId).build();
                //插入消息信息
                inserMsg(content,wxMpXmlMessage.getToUser(),"在线沟通平台",user.getNickname());
                return m;
            } else if(subscribe == 9){
                //插入消息信息
                inserMsg(id.substring(1),userOpenId,user.getNickname(),"在线沟通平台");

                String content = "抱歉，暂未您所选问题的解答,如有问题请拨打咨询电话96510";
                WxMpXmlOutTextMessage m = WxMpXmlOutMessage.TEXT().content(content)
                        .fromUser(wxMpXmlMessage.getToUser())
                        .toUser(userOpenId).build();
                //插入消息信息
                inserMsg(content,wxMpXmlMessage.getToUser(),"在线沟通平台",user.getNickname());
                return m;
            } else {
                //取消关注
                //拿openid去数据库查出wxuser
                userMapper.updateSubscribe(userOpenId, subscribe);
                WxMpXmlOutTextMessage m = WxMpXmlOutMessage.TEXT().content("取消关注")
                        .fromUser(wxMpXmlMessage.getToUser())
                        .toUser(userOpenId).build();
                return m;

            }
        }
    }

    /**
     * 查询业务咨询类型范围
     * @param content
     * @return
     */
    private String generateContent(String content){
        List<WxMpAutoreplyType> typeList = wxMpAutoreplyService.getTypeList();
        for(WxMpAutoreplyType wxMpAutoreplyType:typeList){
            content += "【"+ wxMpAutoreplyType.getTypeId() + "】" + wxMpAutoreplyType.getTypeName() + "\n" ;
        }
        return content;
    }

    private void inserMsg(String content,String openId,String fromUser,String toUser){
        WxMpMessage wxMpMessage = new WxMpMessage();
        wxMpMessage.setMsgContent(content);
        wxMpMessage.setOpenId(openId);
        wxMpMessage.setFromUser(fromUser);
        wxMpMessage.setToUser(toUser);
        MapCacheManager cacheManager = MapCacheManager.getInstance();
        Map<String, String> cashMap = cacheManager.getMapCache();
        wxMpMessage.setDialogId(cashMap.get("dialogId").toString());
        wxMpMsgService.insert(wxMpMessage);
    }

}
